import { User } from '@/AGC/model/User'
import { CloudDBZoneQuery } from '@hw-agconnect/database'
import { cloudDBZone, initCloudDB } from '@/AGC/manager'
import { FoodCollect } from '@/AGC/model/FoodCollect'

/**
 * 执行用户插入
 * @param user 用户
 */
export const executeUpsert = async (user: User) => {
  if (!cloudDBZone) await initCloudDB()

  const cloudDBResult = await cloudDBZone.executeUpsert(user)
  console.log('user-upsert: ' + cloudDBResult)
}

/**
 * 查询用户
 * @param token 用户令牌
 * @returns 用户信息
 */
export const queryUser = async (token: string) => {
  if (!cloudDBZone) await initCloudDB()

  const query = CloudDBZoneQuery.where(User)
  query.equalTo('token', token)
  const snapshot = await cloudDBZone.executeQuery(query)
  return snapshot.getSnapshotObjects()
}

/**
 * 查询用户收藏的食物
 * @param user_id 用户id
 * @returns 用户收藏的食物
 */
export const queryFoodCollect = async (user_id: number) => {
  if (!cloudDBZone) await initCloudDB()

  const query = CloudDBZoneQuery.where(FoodCollect)
  query.equalTo('user_id', user_id)
  const snapshot = await cloudDBZone.executeQuery(query)
  return snapshot.getSnapshotObjects()
}

/**
 * 执行用户收藏食物插入
 * @param foodCollect 用户收藏食物
 */
export const executeUpsertFoodCollect = async (foodCollect: FoodCollect) => {
  if (!cloudDBZone) await initCloudDB()

  const cloudDBResult = await cloudDBZone.executeUpsert(foodCollect)
  console.log('foodCollect-upsert: ' + cloudDBResult)
}

/**
 * 执行用户收藏食物删除
 * @param foodCollect 用户收藏食物
 */
export const executeDeleteFoodCollect = async (foodCollects: FoodCollect[]) => {
  if (!cloudDBZone) await initCloudDB()

  const cloudDBResult = await cloudDBZone.executeDelete(foodCollects)
  console.log('foodCollect-delete: ' + cloudDBResult)
}

/**
 * 查询用户收藏食物表的指定食物
 * @param user_id 用户id
 * @param food_id 食物id
 * @returns 指定的用户收藏的食物
 */
export const queryFoodCollectSingle = async (user_id: number, food_id: number) => {
  if (!cloudDBZone) await initCloudDB()

  const query = CloudDBZoneQuery.where(FoodCollect)
  query.equalTo('user_id', user_id).equalTo('food_id', food_id)
  const snapshot = await cloudDBZone.executeQuery(query)
  return snapshot.getSnapshotObjects()
}
